import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import './app-image-upload.less';
import { Environment } from '@/environments/environment';

@Component({})
export default class AppImageUpload extends Vue {

    /**
     * 表单json字符串
     */
    @Prop() public data !: any;

    @Watch('data', { immediate: true, deep: true })
    onDataChange(newval: any, val: any) {
        if (val) {
            let formData = JSON.parse(newval);
            let upload_arr: Array<string> = [];
            let export_arr: Array<string> = [];
            this.upload_keys.forEach((key: string) => {
                let _value = formData[key];
                if (!_value || Object.is(_value, '')) {
                    return;
                }
                upload_arr.push(`${key}=${_value}`);
            });
            this.export_keys.forEach((key: string) => {
                let _value = formData[key];
                if (!_value || Object.is(_value, '')) {
                    return;
                }
                export_arr.push(`${key}=${_value}`);
            });

            let uploadUrl: string = '/' + Environment.BaseUrl + Environment.UploadFile;
            let downloadUrl: string = '/' + Environment.BaseUrl + Environment.ExportFile;

            this.uploadUrl = `${uploadUrl}?${upload_arr.join('&')}&${this.custom_arr.join('&')}`;
            this.downloadUrl = `${downloadUrl}?${export_arr.join('&')}&${this.custom_arr.join('&')}`;

            this.files.forEach((file: any) => {
                file.url = this.downloadUrl.indexOf('?') !== -1 ? `${this.downloadUrl}&fileid=${file.id}` : `${this.downloadUrl}?fileid=${file.id}`;
            });
        }
    }

    /**
     * 所属表单项名称
     */
    @Prop() public name!: any;

    /**
     * 是否禁用
     */
    @Prop() public disabled?: any;

    /**
     * 表单项值
     */
    @Prop() public value?: any;

    @Watch('value')
    onValueChange(newval: any, val: any) {
        if (newval) {
            this.files = JSON.parse(newval);
            this.files.forEach((file: any) => {
                file.url = this.downloadUrl + '?fileid=' + file.id;
            });
        } else {
            this.files = [];
        }
    }

    /**
     * 上传文件路径
     */
    public uploadUrl = '/' + Environment.BaseUrl + Environment.UploadFile;

    /**
     * 下载文件路径
     */
    public downloadUrl = '/' + Environment.BaseUrl + Environment.ExportFile;

    /**
     * 文件数组
     */
    public files: Array<any> = [];

    /**
     * 预览是否显示
     */
    public dialogVisible: boolean = false;

    /**
     * 预览图片url
     */
    public dialogImageUrl: string = '';

    /**
 * 上传keys
 */
    public upload_keys: Array<any> = [];

    /**
     * 导出keys
     */
    public export_keys: Array<any> = [];

    /**
     * 自定义数组
     */
    public custom_arr: Array<any> = [];

    /**
     * 挂载时调用
     */
    public mounted() {
        if (!this.data) {
            return;
        }
        let form = JSON.parse(this.data);
        if (!form || !form[this.name] || !form[this.name].editorParams || Object.keys(form[this.name].editorParams).length === 0) {
            return;
        }
        let editorParams: any = {};
        let uploadparams: string = '';
        let exportparams: string = '';

        Object.assign(editorParams, form[this.name].editorParams);
        if (editorParams.uploadparams && !Object.is(editorParams.uploadparams, '')) {
            uploadparams = editorParams.uploadparams;
        }
        if (editorParams.exportparams && !Object.is(editorParams.exportparams, '')) {
            exportparams = editorParams.exportparams;
        }
        let upload_keys: Array<string> = uploadparams.split(';');
        let export_keys: Array<string> = exportparams.split(';');
        let custom_arr: Array<string> = [];
        if (editorParams.customparams && !Object.is(editorParams.customparams, '')) {
            Object.keys(editorParams.customparams).forEach((name: string) => {
                if (editorParams.customparams[name]) {
                    custom_arr.push(`${name}=${editorParams.customparams[name]}`);
                }
            });
        }
        this.upload_keys = upload_keys;
        this.export_keys = export_keys;
        this.custom_arr = custom_arr;
    }

    /**
     * 预览
     * @param file 
     */
    public onPreview(file: any) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    }

    /**
     * 下载文件
     * @param file 
     */
    public onDownload(file: any) {
        window.open(file.url);
    }

    /**
     * 删除文件 
     * @param file 
     */
    public onRemove(file: any) {
        if (this.disabled) {
            return;
        }
        let arr: Array<any> = [];
        this.files.forEach((f: any) => {
            if (f.id != file.id) {
                arr.push({ name: f.name, id: f.id });
            }
        });
        let value: String = arr.length > 0 ? JSON.stringify(arr) : '';
        this.$emit('change', value);
    }

    /**
     * 文件上传之前
     */
    public beforeUpload() {
        console.log("文件上传之前");
    }

    /**
     *  文件上传成功 
     */
    public onSuccess(response: any, file: any, fileList: any) {
        let arr: Array<any> = [];
        arr = [...response.files];
        this.files.forEach((f: any) => {
            arr.push({ name: f.name, id: f.id });
        });
        let value: String = arr.length > 0 ? JSON.stringify(arr) : '';
        this.$emit('change', value);
    }

    /**
     * 上传失败回调
     */
    public onError(error: any, file: any, fileList: any) {
        this.$Notice.error({ title: '上传失败' });
    }

    /**
     * 渲染组件
     */
    public render() {
        return (
            <div class="ibiz-picture-upload">
                <ul class="el-upload-list el-upload-list--picture-card">
                    {
                        this.files.map((file: any, index: any) => {
                            return <li key={index} class="el-upload-list__item is-success">
                                <img src={file.url} class="el-upload-list__item-thumbnail" style="min-height:100px;min-width:100px;" />
                                <a class="el-upload-list__item-name">
                                    <i class="el-icon-document"></i> {file.name}
                                </a>
                                <i class="el-icon-close"></i>
                                <label class="el-upload-list__item-status-label">
                                    <i class="el-icon-upload-success el-icon-check"></i>
                                </label>
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview">
                                        <i class="el-icon-zoom-in" on-click={this.onPreview(file)}></i>
                                    </span>
                                    <span class="el-upload-list__item-download">
                                        <i class="el-icon-download" on-click={this.onDownload(file)}></i>
                                    </span>
                                    <span style={{ 'display': this.disabled === true ? 'none' : 'inline-block' }} class="el-upload-list__item-delete">
                                        <i class="el-icon-delete" on-click={this.onRemove(file)}></i>
                                    </span>
                                </span>
                            </li>
                        })
                    }
                </ul>
                <el-upload style={{ 'display': this.disabled === true ? 'none' : 'inline-block' }} show-file-list={false} list-type="picture-card" file-list={this.files} action={this.uploadUrl} before-upload={this.beforeUpload} on-success={this.onSuccess} on-error={this.onError}>
                    <i class="el-icon-plus"></i>
                </el-upload>
                <modal v-model={this.dialogVisible} footer-hide>
                    <img width="100%" src={this.dialogImageUrl} alt="" />
                </modal>
            </div>
        );
    }

}